﻿using System;
using System.Xml;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SharPointInventory
{
    class Helper
    {
        /// <summary>
        /// Return Web Application List in local farm
        /// </summary>
        /// <returns></returns>
        public ListItemCollection GetWebApplicationList()
        {
            SPWebServiceCollection webServiceColl = new SPWebServiceCollection(SPFarm.Local);
            ListItemCollection items = new ListItemCollection();

            foreach (SPWebService webService in webServiceColl)
            {
                foreach (SPWebApplication webApplication in webService.WebApplications)
                {
                    string strWebApp = webApplication.Name + " * " + webApplication.GetResponseUri(SPUrlZone.Default).ToString();
                    ListItem li = new ListItem(strWebApp, webApplication.Id.ToString());
                    items.Add(li);
                }
            }
            return items;
        }
        
        public string ReturnWebAppURL(string strWebApp)
        {
            string strSelectedItem = strWebApp;
            string strWebAppName = strSelectedItem.Substring(0, strSelectedItem.IndexOf('*', 0, strSelectedItem.Length) - 1);

            int startindex = strSelectedItem.IndexOf('*', 0, strSelectedItem.Length) + 2;
            string strWebAppURL = strSelectedItem.Substring(startindex, strSelectedItem.Length - startindex);
            return strWebAppURL;
        }

        public DataTable CreateTabletoStoreSiteCollectionStorageInfo()
        {
            DataTable table = new DataTable("LargeSiteCollectionInfo");
            DataColumn colSiteSize = new DataColumn("Total Size in MB", System.Type.GetType("System.Int64"));
            DataColumn colSiteUrl = new DataColumn("Site Url");
            DataColumn colSiteDiscussionSize = new DataColumn("Discussions Size in MB", System.Type.GetType("System.Int64"));
            DataColumn colMaxQuotaSize = new DataColumn("Quota Size in MB", System.Type.GetType("System.Int64"));
            DataColumn colLastContentModifiedDate = new DataColumn("LastContentModifiedDate");
            DataColumn colLastSecurityModifiedDate = new DataColumn("LastSecurityModifiedDate");
            DataColumn colRecycleBinItemCount = new DataColumn("Recyclebin Items", System.Type.GetType("System.Int32"));
            DataColumn colRecycleBinSize = new DataColumn("RecycleBin Size in MB", System.Type.GetType("System.Int64"));
            table.Columns.Add(colSiteSize);
            table.Columns.Add(colSiteUrl);
            table.Columns.Add(colSiteDiscussionSize);
            table.Columns.Add(colMaxQuotaSize);
            table.Columns.Add(colLastContentModifiedDate);
            table.Columns.Add(colLastSecurityModifiedDate);
            table.Columns.Add(colRecycleBinItemCount);
            table.Columns.Add(colRecycleBinSize);
            return table;
        }

        public DataTable CreateSiteInfoTable()
        {
            DataTable table = new DataTable();
            DataColumn colSiteURL = new DataColumn();
            colSiteURL.ColumnName = "Site URL";
            DataColumn colSiteTemplateName = new DataColumn();
            colSiteTemplateName.ColumnName = "Template Name";
            DataColumn colSiteAlerts = new DataColumn();
            colSiteAlerts.ColumnName = "Total Alerts";
            DataColumn colAllowAnonymous = new DataColumn();
            colAllowAnonymous.ColumnName = "Anonymous";
            DataColumn colAllowRSSFeeds = new DataColumn();
            colAllowRSSFeeds.ColumnName = "Allow RSSFeeds";
            DataColumn colAllowPresence = new DataColumn();
            colAllowPresence.ColumnName = "Presence On";
            DataColumn colHasUniquePermission = new DataColumn();
            colHasUniquePermission.ColumnName = "Unique Permission";
            DataColumn colCreated = new DataColumn();
            colCreated.ColumnName = "Created";
            DataColumn colLastModified = new DataColumn();
            colLastModified.ColumnName = "Last Modified";
            DataColumn colTitle = new DataColumn();
            colTitle.ColumnName = "Title";
            DataColumn colNoCrawl = new DataColumn();
            colNoCrawl.ColumnName = "No Crawl";
            DataColumn colRequestAccessEnabled = new DataColumn();
            colRequestAccessEnabled.ColumnName = "Request Access On";

            table.Columns.Add(colSiteURL);
            table.Columns.Add(colTitle);
            table.Columns.Add(colSiteTemplateName); 
            table.Columns.Add(colCreated);
            table.Columns.Add(colLastModified);
            table.Columns.Add(colNoCrawl);
            table.Columns.Add(colSiteAlerts);
            table.Columns.Add(colAllowAnonymous);
            table.Columns.Add(colHasUniquePermission);
            table.Columns.Add(colAllowRSSFeeds);
            table.Columns.Add(colAllowPresence);
            table.Columns.Add(colRequestAccessEnabled);
            return table;
        }

        public DataTable CreateTabletoStoreSiteACLs()
        {
            DataTable tableSiteACLs = new DataTable("Site ACLs");
            DataColumn colSiteUrl = new DataColumn("Sites with large number of ACLs");
            DataColumn colACLCount = new DataColumn("Total Unique Users or Groups", System.Type.GetType("System.Int32"));
            tableSiteACLs.Columns.Add(colSiteUrl);
            tableSiteACLs.Columns.Add(colACLCount);
            return tableSiteACLs;
        }

        public DataTable CreateTabletoStoreListVersionInfo()
        {
            DataTable tableListVersionInfo = new DataTable("ListVersionInfo");
            DataColumn colListName = new DataColumn("List Name");
            DataColumn colListSiteUrl = new DataColumn("Site Url");
            DataColumn colListCount = new DataColumn("Total Items", System.Type.GetType("System.Int32"));
            DataColumn colListRootFolderCount = new DataColumn("No of Items in Root", System.Type.GetType("System.Int32"));
            DataColumn colLastItemModifiedDate = new DataColumn("Last Item Modified Date");
            tableListVersionInfo.Columns.Add(colListName);
            tableListVersionInfo.Columns.Add(colListSiteUrl);
            tableListVersionInfo.Columns.Add(colListCount);
            tableListVersionInfo.Columns.Add(colListRootFolderCount);
            tableListVersionInfo.Columns.Add(colLastItemModifiedDate);
            return tableListVersionInfo;
        }

        public DataTable CreateTabletoStoreDatabaseInfo()
        {
            DataTable tableDatabaseInfo = new DataTable("Content Databases");
            DataColumn colName = new DataColumn("Name");
            DataColumn colDiskSize = new DataColumn("Disk Size required to backup in GB", System.Type.GetType("System.Int64"));
            DataColumn colCurrentSiteCount = new DataColumn("Current SiteCount", System.Type.GetType("System.Int32"));
            DataColumn colWarningSiteCount = new DataColumn("Warning SiteCount", System.Type.GetType("System.Int32"));
            DataColumn colMaximumSiteCount = new DataColumn("Maximum SiteCount", System.Type.GetType("System.Int32"));
            DataColumn colStatus = new DataColumn("Status");
            DataColumn colServer = new DataColumn("SQLServer Instance");
            DataColumn colID = new DataColumn("ID");

            tableDatabaseInfo.Columns.Add(colName);
            tableDatabaseInfo.Columns.Add(colDiskSize);
            tableDatabaseInfo.Columns.Add(colCurrentSiteCount);
            tableDatabaseInfo.Columns.Add(colWarningSiteCount);
            tableDatabaseInfo.Columns.Add(colMaximumSiteCount);
            tableDatabaseInfo.Columns.Add(colStatus);
            tableDatabaseInfo.Columns.Add(colServer);
            tableDatabaseInfo.Columns.Add(colID);
            return tableDatabaseInfo;
        }

        public DataTable CreateTabletoStoreUnghostedPages()
        {
            DataTable tableUnGhostedPages = new DataTable("UnGhostedPages");
            DataColumn colName = new DataColumn("Name");
            DataColumn colWebUrl = new DataColumn("Url");
            DataColumn colTotalSize = new DataColumn("Total Size", System.Type.GetType("System.Int64"));
            DataColumn colMajorVersion = new DataColumn("MajorVersion");
            DataColumn colMinorVersion = new DataColumn("MinorVersion");
            DataColumn colModifiedBy = new DataColumn("ModifiedBy");
            DataColumn colCheckedOutBy = new DataColumn("CheckedOutBy");
            DataColumn colCheckedOutDate = new DataColumn("CheckedOutDate");
            tableUnGhostedPages.Columns.Add(colName);
            tableUnGhostedPages.Columns.Add(colWebUrl);
            tableUnGhostedPages.Columns.Add(colTotalSize);
            tableUnGhostedPages.Columns.Add(colMajorVersion);
            tableUnGhostedPages.Columns.Add(colMinorVersion);
            tableUnGhostedPages.Columns.Add(colModifiedBy);
            tableUnGhostedPages.Columns.Add(colCheckedOutBy);
            tableUnGhostedPages.Columns.Add(colCheckedOutDate);
            return tableUnGhostedPages;
        }

        public DataTable CreateTabletoStoreCheckedOutDocs()
        {
            DataTable tableCheckedOutDocs = new DataTable("CheckedOut Docs");
            DataColumn colName = new DataColumn("Name");
            DataColumn colWebUrl = new DataColumn("Url");
            DataColumn colCheckedOutBy = new DataColumn("CheckedOutBy");
            DataColumn colCheckedOutDate = new DataColumn("CheckedOutDate");
            DataColumn colModifiedBy = new DataColumn("ModifiedBy");
            DataColumn colModifiedDate = new DataColumn("ModifiedDate");
            tableCheckedOutDocs.Columns.Add(colName);
            tableCheckedOutDocs.Columns.Add(colWebUrl);            
            tableCheckedOutDocs.Columns.Add(colCheckedOutBy);
            tableCheckedOutDocs.Columns.Add(colCheckedOutDate);
            tableCheckedOutDocs.Columns.Add(colModifiedBy);
            tableCheckedOutDocs.Columns.Add(colModifiedDate);
            return tableCheckedOutDocs;
        }

        public DataTable CreateTabletoStoreSiteSolutions()
        {
            DataTable tableSiteSolutions = new DataTable("Solutions");
            DataColumn colSolutionID = new DataColumn("SolutionId");
            DataColumn colName = new DataColumn("Name");
            DataColumn colStatus = new DataColumn("Status");
            DataColumn colSignature = new DataColumn("Signature");
            DataColumn colHasAssemblies = new DataColumn("HasAssemblies");
            DataColumn colSite = new DataColumn("SiteUrl");

            tableSiteSolutions.Columns.Add(colName);
            tableSiteSolutions.Columns.Add(colSolutionID);
            tableSiteSolutions.Columns.Add(colStatus);
            tableSiteSolutions.Columns.Add(colSignature);
            tableSiteSolutions.Columns.Add(colHasAssemblies);
            tableSiteSolutions.Columns.Add(colSite);
            return tableSiteSolutions;
        }

        public DataTable CreateTableToStoreListTemplates()
        {
            DataTable tableListTemplates = new DataTable("ListTemplates");
            DataColumn colName = new DataColumn("Template Name");
            DataColumn colSiteUrl = new DataColumn("Site URL");
            tableListTemplates.Columns.Add(colName);
            tableListTemplates.Columns.Add(colSiteUrl);
            return tableListTemplates;
        }

        public void AddRowstoUnGhostedPagesTable(SPFile file, DataTable tableUnGhostedPages, string url)
        {
            DataRow row = null;

            if (file.Name.Contains(".aspx"))
            {
                if (file.CustomizedPageStatus == SPCustomizedPageStatus.Customized)
                {
                    row = tableUnGhostedPages.NewRow();

                    row["Name"] = file.Name.ToString();
                    row["Url"] = url;
                    row["Total Size"] = Convert.ToInt64(file.TotalLength);
                    row["MajorVersion"] = file.MajorVersion.ToString();
                    row["MinorVersion"] = file.MinorVersion.ToString();
                    row["ModifiedBy"] = file.ModifiedBy.ToString();

                    string s1 = "";
                    string s2 = "";

                    if (file.CheckedOutBy != null)
                    {
                        s1 = file.CheckedOutBy.ToString();
                        s2 = file.CheckedOutDate.ToString();
                    }

                    row["CheckedOutby"] = s1;
                    row["CheckedOutDate"] = s2;
                    tableUnGhostedPages.Rows.Add(row);
                }
            }
        }

        public void AddRowstoCheckedOutDocsTable(SPFile file, DataTable tableCheckedOutDocs, string url)
        {
            DataRow row = null;
            if (file.CheckedOutBy != null)
            {
                row = tableCheckedOutDocs.NewRow();
                row["Name"] = file.Name;
                row["CheckedOutBy"] = file.CheckedOutBy;
                row["CheckedOutDate"] = file.CheckedOutDate;
                row["ModifiedBy"] = file.ModifiedBy;
                row["ModifiedDate"] = file.TimeLastModified;
                row["Url"] = url;
                tableCheckedOutDocs.Rows.Add(row);
            }
        }

        public DataTable processDocumentStatsInfo(DataTable table)
        {
            DataTable tableDocs = new DataTable();
            DataColumn colDocSize = new DataColumn("Document Size in KB", System.Type.GetType("System.Int64"));
            DataColumn colTotalDocSizeIncludingVersion = new DataColumn("Total Size including versions in KB", System.Type.GetType("System.Int64"));
            DataColumn colDirectory = new DataColumn("Directory");
            DataColumn colFileName = new DataColumn("File Name");
            DataColumn colWebUrl = new DataColumn("Web Url");
            tableDocs.Columns.Add(colDocSize);
            tableDocs.Columns.Add(colTotalDocSizeIncludingVersion);
            tableDocs.Columns.Add(colFileName);
            tableDocs.Columns.Add(colDirectory);
            tableDocs.Columns.Add(colWebUrl);

            foreach (DataRow r in table.Rows)
            {
                DataRow row = tableDocs.NewRow();
                row["Document Size in KB"] = ConvertBytestoKB(Convert.ToInt64(r["Size"]));
                row["Total Size including versions in KB"] = ConvertBytestoKB(Convert.ToInt64(r["TotalSize"]));
                row["Directory"] = r["Directory"];
                row["File Name"] = r["LeafName"];
                row["Web Url"] = r["WebUrl"];
                tableDocs.Rows.Add(row);
            }
            return tableDocs;
        }

        public DataTable processListLibraryStatsInfo(DataTable table)
        {
            DataTable tableListInfo = new DataTable();
            DataColumn colTitle = new DataColumn("Title");
            DataColumn colSize = new DataColumn("Size in MB", System.Type.GetType("System.Int64"));
            DataColumn colItemCount = new DataColumn("Total Items or Files", System.Type.GetType("System.Int32"));
            DataColumn colDirectory = new DataColumn("Directory");
            DataColumn colListName = new DataColumn("Leaf Name");
            DataColumn colWebUrl = new DataColumn("Web Url");
            DataColumn colListGuid = new DataColumn("List Guid");
            tableListInfo.Columns.Add(colTitle);
            tableListInfo.Columns.Add(colSize);
            tableListInfo.Columns.Add(colItemCount);
            tableListInfo.Columns.Add(colListName);
            tableListInfo.Columns.Add(colDirectory);
            tableListInfo.Columns.Add(colWebUrl);
            tableListInfo.Columns.Add(colListGuid);

            foreach (DataRow r in table.Rows)
            {
                DataRow row = tableListInfo.NewRow();
                row["Title"] = r["Title"];
                row["Size in MB"] = ConvertBytestoMB(Convert.ToInt64(r["Size"]));
                row["Total Items or Files"] = r["ItemCount"];
                row["Directory"] = r["Directory"];
                row["Leaf Name"] = r["LeafName"];
                row["Web Url"] = r["WebUrl"];
                row["List Guid"] = r["ListGuid"];
                tableListInfo.Rows.Add(row);
            }
            return tableListInfo;
        }

        public long ConvertBytestoMB(long bytes)
        {
            decimal size = decimal.Divide(Convert.ToInt64(bytes), 1048576);
            long listsize = Convert.ToInt64(decimal.Round(size, 2));
            return listsize;
        }

        public long ConvertBytestoKB(long bytes)
        {
            decimal size = decimal.Divide(bytes, 1024);
            long filesize = Convert.ToInt64(decimal.Round(size, 2));
            return filesize;
        }

        public ulong ConvertBytestoGB(ulong bytes)
        {
            decimal size = decimal.Divide(bytes, 1073741824);
            ulong filesize = Convert.ToUInt64(decimal.Round(size, 2));
            return filesize;
        }

        public string FormatBytes(long Bytes)
        {
            string filesize;
            if (Bytes >= 1073741824)
            {
                decimal size = decimal.Divide(Bytes, 1073741824);
                filesize = string.Format("{0:##.##} GB", size);
            }
            else if (Bytes >= 1048576)
            {
                decimal size = decimal.Divide(Bytes, 1048576);
                filesize = string.Format("{0:##.##} MB", size);
            }
            else if (Bytes >= 1024)
            {
                decimal size = decimal.Divide(Bytes, 1024);
                filesize = string.Format("{0:##.##} KB", size);
            }
            else if (Bytes > 0 & Bytes < 1024)
            {
                decimal size = Bytes;
                filesize = string.Format("{0:##.##} Bytes", size);
            }
            else
            {
                filesize = "0 Bytes";
            }
            return filesize;

        }

    }
}
